<?php

class OrderController extends UserController
{
    public function actionIndex()
    {
        $model = new Service('search');
        $widget = $this->createWidget('ext.EDataTables.EDataTables', array(
            'id' => 'products',
            'dataProvider' => $model->search(),
            'ajaxUrl' => url('order/index'),
            'columns' => array(
//                    array(
//                        'header' => 'Image',
//                        'type' => 'raw',
//                        'value' => 'CHtml::image($data->get_avatar_by_size(80,80),"",array("class"=>"thumb_on_list"))',
//                        'htmlOptions' => array(
//                            'width' => '10%',
//                            'class' => 'text-center',
//                        ),
//                    ),
                    array(
                        'header' => 'Name',
                        'name' => 's_name',
                        'type' => 'raw',
                        'value' => 'CHtml::link($data->s_name,$data->editUrl,array("target"=>"blank"))',
                        'filter' => CHtml::textField('Service[s_name]', $model->s_name, array('placeHolder' => 'Search name')),
                    ),
//                    array(
//                        'header' => 'Category',
//                        'name' => 'category_id',
//                        'type' => 'raw',
//                        'value' => $this->isAdmin ? 'CHtml::link(@$data->category->name,@$data->category->editUrl,array("target"=>"blank"))' : '@$data->category->name',
//                        'filter' => CHtml::dropDownList("Service[category_id]", $model->category_id, $categories_data, array(
//                            "data-rel" => "chosen"
//                            )),
//                        'htmlOptions' => array(
//                        ),
//                    ),
//                    array(
//                        'header' => 'Merchant',
//                        'name' => 'author_id',
//                        'type' => 'raw',
//                        'value' => $this->isAdmin ? 'CHtml::link(@$data->user->name,@$data->user->editUrl,array("target"=>"blank"))' : '@$data->user->name',
//                        'filter' => $this->isAdmin ? CHtml::dropDownList("Service[author_id]", $model->author_id, Merchant::get_all_merchant(FALSE, TRUE), array("data-rel" => "chosen")) : false,
//                        'htmlOptions' => array(
//                        ),
//                    ),
//                    array(
//                        'header' => 'Duration',
//                        #'name'=>'duration',
//                        'type' => 'raw',
//                        'value' => '$data->durationTime',
//                        'filter' => false,
//                        'htmlOptions' => array(
//                        //'width'=>'%'
//                        ),
//                    ),
//                    array(
//                        'header' => 'Price',
//                        'type' => 'raw',
//                        'value' => '$data->getPriceFormat(false)',
//                        'filter' => false,
//                        'htmlOptions' => array(
//                        //'width'=>'%'
//                        ),
//                    ),
//                    array(
//                        'header' => 'Points',
//                        'type' => 'raw',
//                        'value' => '$data->user!=null? ($data->user->service!=null? $data->price * $data->user->service->money_to_points:0):0',
//                        'filter' => false,
//                        'htmlOptions' => array(
//                        //'width'=>'%'
//                        ),
//                    ),
//                    //Book Online
//                    array(
//                        'header' => 'Book Online',
//                        'type' => 'raw',
//                        'value' => '$data->book_online ? "<i class=\"icon-ok\"></i>":0',
//                        'filter' => false,
//                        'htmlOptions' => array(
//                        //'width'=>'%'
//                        ),
//                    ),
//                    array(
//                        'class' => 'CButtonColumn',
//                        'template' => '{update}',
//                        'htmlOptions' => array(
//                            'width' => '10%'
//                        ),
//                        'buttons' => array(
//                            'update' => array(
//                                'url' => 'url("service/update",array("id"=>$data->sid))',
//                                'imageUrl' => false,
//                                'label' => '<i class="icon-edit"></i>',
//                                'options' => array(
//                                    'class' => 'btn btn-info',
//                                    'target' => '_blank',
//                                    'title' => 'Update'
//                                ),
//                            ),
//                        ),
//                    ),
                )
        ));
        if (!Yii::app()->getRequest()->getIsAjaxRequest())
        {
            $this->render('index', array('widget' => $widget,));
            return;
        }
        else
        {
            json_encode($widget->getFormattedData(intval($_REQUEST['sEcho'])));
            Yii::app()->end();
        }
    }

    public function actionDetail()
    {
        if (!isset($_GET['pk']))
        {
            throw new CHttpException(404, 'Order not found!');
        }
        //lấy dữ liệu Order theo order_key
        $model = Orders::model()->find('order_key=:p', array(
            ':p' => $_GET['pk']
        ));

        if (!$model || !$model->service || !$model->service->user || !$model->customer)
        {
            throw new CHttpException(404, 'Order not found or data error!');
        }

        //Danh sách staff thực hiện order này
        $performOrder = $this->getPerformOrder($model->order_id);



        if ($model->status == Orders::STATUS_CANCEL)
        {

            $this->redirect(Yii::app()->createUrl('order/index'));
        }

        if ($model->status == Orders::STATUS_COMPLETED)
        {
            //lấy dữ liệu Payment
            $payment = $this->getPayment($model->order_id);

            //lấy dữ liệu Receipt theo Order đã "COMPLETED"
            $receipt_value = $this->getReceipt($model->order_id);

            $this->render('view', array(
                'receipt' => $receipt_value,
                'perform' => $performOrder,
                'payment' => $payment,
            ));
        }
        elseif ($model->status == Orders::STATUS_COMPLETED_webmaster OR $model->status == Orders::STATUS_PENDING OR $model->status == Orders::STATUS_CONFIRMED)
        {
            $customer_id = $model->customer->id;
            //Tạo RetailItems
            if (isset($_POST['RetailOrderItem']))
            {
                $this->createRetailOrder($customer_id, $model->order_id, $model->service->author_id);
            }
            //Lưu những Staff gán cho order này
            if (isset($_POST['staff']))
            {
                foreach ($_POST['staff'] as $staff)
                {
                    if (!Orders::checkAddedStaff($staff, $model->order_id))
                    {
                        $perform             = new PerformOrder();
                        $perform->order_id   = $model->order_id;
                        $perform->staff_ukey = $staff;
                        $perform->save();
                    }
                }
            }

            $qty = isset($_POST['qty']) ? intval($_POST['qty']) : 1;

            //
            $discount      = $model->hotdeal_discount + $model->first_discount;
            $discount_type = isset($_POST['discount_type']) ? $_POST['discount_type'] : '%';

            /**
             * Customer Package
             * Check $_GET['usePackage'] nếu muốn dùng package để thanh toán cho order
             * Check $customer_package kiểm tra nếu customer này có package cho service này và package chưa limit
             */
            $customer_package = $this->getCustomerPackage($customer_id, $model->s_id);

            if (isset($_GET['usePackage']) && $customer_package)
            {
                $pack       = $customer_package->package;
                $pack_price = $pack->price / $pack->limit;
                $price      = $model->s_price * $qty - $pack_price;
            }
            else
            {
                $price = $model->s_price * $qty;
            }
            $discount_value = ($discount_type == '%') ? ($discount * $price / 100) : $discount;
            //Update: Lấy tax đã lưu vào Order
            $tax_value      = $model->s_price * $qty * $model->tax / 100; //Lấy giá gốc

            $final  = $price - $discount_value + $tax_value;
            $amount = isset($_POST['amount']) ? (float) ($_POST['amount']) : 0;
            $method = isset($_POST['method']) ? intval($_POST['method']) : 0;
            if ($amount > 0)
            {
                //Tạo record Receipt
                $this->createReceipt($discount, $discount_type, $final, $model, $tax_value, $qty);
                //Lưu thông tin thanh toán order
                $payment               = new Payment();
                $payment->amount       = $amount;
                $payment->method       = $method;
                $payment->order_id     = $model->order_id;
                $payment->payment_date = time();
                $payment->type         = Payment::TYPE_APPOINT;
                if ($payment->save())
                {
                    $payment->payment_key = $payment->genPaymentKey();
                    $payment->save();
                }
                /**
                 * @VOITHAN: Update Appoint Status
                 */
                Appoint::model()->updateByPk($model->apt_id, array('status' => Appoint::STATUS_CHECKOUT));

                if ($model->appoint->type == Appoint::TYPE_APPOINTMENT)
                {
                    Appoint::model()->updateByPk($model->apt_id, array('status' => Appoint::STATUS_CHECKOUT));
                }
                elseif ($model->appoint->type == Appoint::TYPE_ROOM)
                {
                    $apt_cus               = AptCustomer::model()->find("apt_id=:a AND customer_id=:c", array(
                        ":a" => $model->apt_id,
                        ":c" => $model->customer->id
                    ));
                    $apt_cus->check_status = AptCustomer::CHECK_STATUS_CHECKOUT;
                    $apt_cus->save();
                }

                $model->status = Orders::STATUS_COMPLETED;


                if ($model->save())
                {
                    //Nếu có sử dụng Package cho Order này thì tạo PackageOrder
                    //và cập nhật thông tin vào PackageCustomer
                    if (isset($_GET['usePackage']) && $customer_package)
                    {
                        $this->AddPackage($model->cus_ckey, $model->order_id);
                    }
                    Yii::app()->request->redirect(Yii::app()->createUrl("order/detail", array(
                                'pk' => $_GET['pk'],
                    )));
                }
            }

            $this->render('_orderPending', array(
                'order'            => $model,
                'tax_value'        => $tax_value,
                'final'            => $final,
                'qty'              => $qty,
                'discount'         => $discount,
                'discount_type'    => $discount_type,
                'perform'          => $performOrder,
                'customer_package' => $customer_package
            ));
        }
    }

    /**
     * Lưu thông tin thanh toán của Order vào receipt
     * @param type $discount
     * @param type $discount_type
     * @param type $final
     * @param type $order Order record
     * @param type $tax_value
     * @param type $qty
     */
    private function createReceipt($discount, $discount_type, $final, $order, $tax_value, $qty)
    {
        $receipt                   = new Receipt();
        $receipt->discount         = $discount;
        $receipt->discount_type    = $discount_type;
        $receipt->final_price      = $final;
        $receipt->list_price       = $order->s_price;
        $receipt->order_id         = $order->order_id;
        $receipt->tax              = $tax_value; //Giá trị tax đã tính
        $receipt->qty              = $qty;
        $receipt->receipt_date     = time();
        $receipt->item_description = "<b>{$order->service->s_name}</b><br/>";
        $receipt->item_description .= $order->formartDate() . "<br/>";
        $receipt->item_description .= "Duration: {$order->service->duration} minute<br/>";
        $receipt->item_description .= "Booking: #$order->apt_id<br/>";
        if ($receipt->save())
        {
            $receipt->receipt_key = $receipt->genReceiptKey();
            $receipt->save();
        }
    }

    /**
     * Send Receipt Email
     */
    public function actionSendEmail()
    {
        if (!isset($_GET['pk']))
        {
            throw new CHttpException(404, 'Order not found or data error!');
        }
        $model = Orders::model()->find('order_key=:p', array(
            ':p' => $_GET['pk']
        ));
        if ($model == NULL)
        {
            throw new CHttpException(404, 'Order not found or data error!');
        }

        //lấy dữ liệu PerformOrder Order
        $performOrder = $this->getPerformOrder($model->order_id);

        //lấy dữ liệu Receipt theo Order đã "COMPLETED"
        $receipt = $this->getReceipt($model->order_id);

        //lấy dữ liệu Payment
        $payment = $this->getPayment($model->order_id);

        //Link đến file view của Receipt
        $body = $this->renderInternal(Yii::getPathOfAlias('webroot.themes')
                . DIRECTORY_SEPARATOR . "webmaster" . DIRECTORY_SEPARATOR . "views" .
                DIRECTORY_SEPARATOR . "order" . DIRECTORY_SEPARATOR . "_receipt.php", array(
            'model'   => $receipt, 'perform' => $performOrder, 'payment' => $payment), true);

        $sendMail                   = New MyEmail();
        $sendMail->title_mail_order = "Receipt for Order#{$model->order_key} at webmaster";
        $sendMail->to               = $model->customer->user->email;
        $sendMail->body             = $body;
        $sendMail->send();

        Yii::app()->user->setFlash('success', 'Emailed Receipt Successfully!');
        Yii::app()->request->redirect(Yii::app()->createUrl("order/detail", array(
                    'pk' => $_GET['pk'],
        )));
    }

    private function createRetailOrder($customer_id, $order_id, $biz_id)
    {
        //Check stock, check id, check qty
        $status = 0;
        foreach ($_POST['RetailOrderItem'] as $v)
        {
            $item = Retail::getRecordById($v['id']);
            if ($v['qty'] <= 0)
            {
                Yii::app()->user->setFlash('error', 'Quantity must be greater than zero');
                $this->refresh();
                break;
            }
            elseif ($v['id'] == 0)
            {
                Yii::app()->user->setFlash('error', 'Please select at least one item');
                $this->refresh();
                break;
            }
            //Record item trong retail order
            elseif ($v['qty'] > $item->available)//Stock unavailable
            {
                $msg = "Add item {$item->name} error, Stock status: {$item->available} item(s) left. Please change quantity";
                Yii::app()->user->setFlash('error', $msg);
                $this->refresh();
                break;
            }
            else
            {
                $status = 1;
            }
        }
        if ($status == 1)
        {
            //Tạo RetailOrder
            $model_order                 = new RetailOrder();
            $model_order->customer_id    = $customer_id;
            $model_order->order_id       = $order_id;
            $model_order->payment_method = RetailOrder::PAYMENT_CASH;
            $model_order->date_created   = time();
            $model_order->status         = RetailOrder::STATUS_COMPLETED;
            $model_order->biz_id         = $biz_id;
            $model_order->total_price    = 0;

            if ($model_order->validate() && $model_order->save())
            {
                //Tạo RetailOrderItem
                $total = 0;
                foreach ($_POST['RetailOrderItem'] as $v)
                {
                    $item                = Retail::getRecordById($v['id']);
                    $total += ($v['qty'] * $item->price);
                    $orderItem           = new RetailOrderItem();
                    $orderItem->order_id = $model_order->id;
                    $orderItem->item_id  = $v['id'];
                    $orderItem->qty      = $v['qty'];
                    $orderItem->save();
                }

                //Cập nhật lại avaible cho Retail item
                foreach ($model_order->items as $v)
                {
                    $retail_model = Retail::model()->findByPk($v->item->id);
                    $retail_model->available -= $v->qty;
                    $retail_model->save();
                }
                $model_order->key         = $model_order->genOkey();
                //Cập nhật lại total
                $model_order->total_price = $total;
                $model_order->save();
                if (isset($_POST['RetailOrder']))
                {
                    //Tạo receipt cho RetailOrder
                    $receipt           = new RetailReceipt();
                    $receipt->order_id = $model_order->id;
                    if ($_POST['RetailOrder']['discount'] != NULL)
                    {
                        $receipt->discount      = $_POST['RetailOrder']['discount'];
                        $receipt->discount_type = $_POST['RetailOrder']['discount_type'] == 'm' ? '$' : '%';
                    }
                    $receipt->final_price  = trim($_POST['RetailOrder']['total_price'], '$');
                    $receipt->tax          = trim($_POST['RetailOrder']['tax'], '$');
                    $receipt->receipt_date = time();
                    if ($receipt->validate() && $receipt->save())
                    {
                        $receipt->receipt_key = $receipt->genReceiptKey();
                        $receipt->save();
//                        //Lưu Phương thức thanh toán 
//                        $payment = new Payment();
//                        $payment->amount = $receipt->final_price;
//                        $payment->method = $_POST['method'];
//                        $payment->order_id = $model_order->id;
//                        $payment->payment_date = time();
//                        $payment->type = Payment::TYPE_RETAIL;
//                        if ($payment->save())
//                        {
//                            $payment->payment_key = $payment->genPaymentKey();
//                            $payment->save();
//                        }
                    }
                }
            }
        }
    }

    /**
     * Nếu Customer có mua Package cho service này thì return record package đã gán với Customer
     * @param type $customer_id
     * @param type $service_id
     * @return record packageCustomer
     */
    private function getCustomerPackage($customer_id, $service_id)
    {
        $cri            = new CDbCriteria();
        $cri->condition = "s_id=$service_id";
        $pack_sv_model  = PackageService::model()->findAll($cri);
        //Check service này có package nào không
        if (!$pack_sv_model)
        {
            return NULL;
        }
        foreach ($pack_sv_model as $v)
        {

            if ($v->package != NULL)
            {

                foreach ($v->package->customers as $pack_cus)
                {
                    //Nếu customer này đã gán và available thì return record packageCustomer đó
                    if ($pack_cus->customer_id == $customer_id AND $pack_cus->available > 0)
                    {
                        return $pack_cus;
                    }
                }
            }
        }
    }

    public function getPerformOrder($orderId)
    {
        return PerformOrder::model()->findAll('order_id=:p', array(
                    ':p' => $orderId
        ));
    }

    public function getReceipt($orderId)
    {
        //lấy dữ liệu Receipt theo Order đã "COMPLETED"
        $crite = $this->__Criteria($orderId);
        return Receipt::model()->find($crite);
    }

    public function getPayment($orderId)
    {
        $crit = $this->__Criteria($orderId);
        return Payment::model()->find($crit);
    }

    protected function __Criteria($orderId = NULL)
    {
        $cri = new CDbCriteria();
        if ($orderId != NULL && !empty($orderId))
        {
            $cri->condition = 'order_id=:p';
            $cri->params    = array(
                ':p' => $orderId
            );
        }
        $cri->order = 'id DESC';
        return $cri;
    }

    public function actionChangeStt()
    {
        $pk = (!isset($_GET['pk']) or $_GET['pk'] == NULL) ? FALSE : $_GET['pk'];
        if (!$pk)
        {
            throw new CHttpException(404, 'Not found');
        }
        //lấy dữ liệu Order theo [pk]
        $model = Orders::model()->find('order_key=:p', array(
            ':p' => $pk
        ));

        Orders::model()->updateByPk($model->order_id, array('status' => Orders::STATUS_CANCEL));
        Yii::app()->request->redirect(Yii::app()->createUrl("order/index"));
    }

    private function AddPackage($customer_ckey, $order_id)
    {
        $customer_id   = Customer::getIdByCkey($customer_ckey);
        $customer_pack = PackageCustomer::model()->find("customer_id=$customer_id AND package_id=" . $_GET['usePackage']);
        if (!$customer_pack or $customer_pack->available == 0)
        {
            throw new CHttpException(404, 'Wrong package or customer');
        }
        else
        {
            $customer_pack->used_times+=1;
            $customer_pack->available-=1;

            if ($customer_pack->validate())
            {
                if ($customer_pack->save())
                {
                    $pack_order                   = new PackageOrder();
                    $pack_order->pack_customer_id = $customer_pack->id;
                    $pack_order->order_id         = $order_id;
                    $pack_order->date             = time();
                    $pack_order->save();
                }
            }
        }
    }

}
